﻿param(
    [string]$profilePath=("{0}\microsoft.powershellise_profile.ps1" -f $(Split-Path -Parent $profile))
)
$script:scriptdir = split-path -parent $MyInvocation.MyCommand.path
$addonName = $(. $(join-path $scriptdir "Launcher.ps1") -getName)
$destPath = join-Path $env:APPDATA ("PSISEAddons\{0}" -f $addonName)
if(!(Test-Path $(Split-Path -parent $profilePath)))
{
    $null = mkdir -force $(Split-Path -parent $profilePath)
}
if(!(Test-Path $profilePath))
{
    $null = New-Item -ItemType file -value $null -Path $profilePath
}
$addonString = (@"
#region {0} installation
. {1}\launcher.ps1
#endregion
"@ -f  $addonName, $destPath)

if(test-Path $destPath)
{
	Write-Host "Addon already present."
	$title = "Overwrite"
	$message = "Do you want to overwrite?"

	$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
		"Delete previous version and replace by the current one."

	$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
		"Retains all the files in the folder."

	$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

	$result = $host.ui.PromptForChoice($title, $message, $options, 0) 

	switch ($result)
	{
		0 {
			"Overwriting..."
			$null = remove-Item -Force -Recurse $destPath 
		}
		1 {
			"Addon not installed. Exiting..."
			Start-Sleep -Seconds 3
			exit
		}
	}
	
}

$null = new-Item -Path $destPath -ItemType directory -Force

try{
	$null = copy-Item -Path $(join-Path $script:scriptdir "launcher.ps1") -Destination $destPath -ErrorAction stop
	$null = copy-Item -Path $(join-Path $script:scriptdir "*.dll") -Destination $destPath -ErrorAction stop
}catch{
	Write-Host "Installation failed!"
	$null = $host.UI.RawUI.ReadKey()
	exit
}


$profileContents = Get-Content $profilePath
if($profileContents -notcontains ("#region {0} installation" -f $addonName))
{
    $profileContents += $addonString
    Set-Content $profilePath -Value $profileContents -Force
    Write-Host "Installation done!"
}
else
{
    Write-Host "Addon already installed."
}
write-Host "Press a key to exit"
$null = $host.UI.RawUI.ReadKey()